package com.djzh.insightconnector.mockproject.mock;

import com.djzh.insightconnector.mockproject.domain.*;
import org.springframework.web.bind.annotation.*;

import java.nio.charset.StandardCharsets;
import java.util.*;

@RestController
@RequestMapping("/dssn/auth/identity")
public class MockApiController {

    /**
     * 注册连接器 connectorRegistry
     *
     * @return 模拟响应数据
     */
    @PostMapping("/connectorRegistry")
    public ConnBaseResponse<Map<String, Object>> mockConnectorRegistry(@RequestBody ConnectorInfo connectorInfo) {
        Map<String, Object> data = new HashMap<>();
        data.put("processId", "dssn-005bq03WY3RG5O4KKQr1E0yfxJ4");
        data.put("reportTime", "1751349623066");

        ConnBaseResponse<Map<String, Object>> result = new ConnBaseResponse<>();
        result.setStatusCode("200");
        result.setMessage("success");
        result.setData(data);
        result.setTimestamp(new Date().toString());
        return result;
    }

    /**
     * 业务状态查询
     *
     * @return 模拟响应数据
     */
    @PostMapping("/formStatusQuery")
    public ConnBaseResponse<Map<String, Object>> mockFormStatusQuery(@RequestBody FormStatusQueryVO formStatusQueryVO) {

        Map<String, Object> data = new HashMap<>();
        data.put("processId", "dssn-005bq03WY3RG5O4KKQr1E0yfxJ4");
        data.put("processStatus", "1");
        data.put("identityId", "591120116722997404G1200MHOB3FJ7W");

        ConnBaseResponse<Map<String, Object>> result = new ConnBaseResponse<>();
        result.setStatusCode("200");
        result.setMessage("success");
        result.setData(data);
        result.setTimestamp(new Date().toString());
        return result;
    }

    /**
     * 模拟证书申请接口
     *
     * @return 模拟响应数据
     */
    @PostMapping("/applyCorporationCert")
    public ConnBaseResponse<Map<String, Object>> mockApplyCorporationCert(@RequestBody CertApplyRequest certApplyRequest) {

        Map<String, Object> data = new HashMap<>();
        data.put("processType", "8");
        data.put("processId", "dssn-005bq03WY3RG5O4KKQr1E0yfxJ4");
        data.put("certApplyStatus", "0");

        ConnBaseResponse<Map<String, Object>> result = new ConnBaseResponse<>();
        result.setStatusCode("200");
        result.setMessage("success");
        result.setData(data);
        result.setTimestamp(new Date().toString());
        return result;
    }

    /**
     * 证书申请状态查询及下载
     *
     * @return 模拟响应数据
     */
    @PostMapping("/downloadCert")
    public ConnBaseResponse<Map<String, Object>> mockDownloadCert(@RequestBody DownloadCertVO downloadCertVO) {

        Map<String, Object> data = new HashMap<>();
        data.put("certApplyStatus", "1");
        data.put("certApplyMsg", "证书申请异常信息");
        data.put("certId", "1986726533681983489");
        data.put("signCert", "-----BEGIN CERTIFICATE-----\\nMIIC9jCCApugAwIBAgIJAKGHTypeExuzMAwGCCqBHM9VAYN1BQAwJDELMAkGA1UE\\nBhMCQ04xFTATBgNVBAMMDENNQ0EgUm9vdCBDQTAeFw0yNTExMDcwOTIxMzFaFw0y\\nNjExMDcwOTIxMzFaMEIxCzAJBgNVBAYTAkNOMTMwMQYDVQQDDCrkuK3lm73np7vl\\niqjpgJrkv6Hpm4blm6LlpKnmtKXmnInpmZDlhazlj7gwWTATBgcqhkjOPQIBBggq\\ngRzPVQGCLQNCAATP0SaujDiEqeHWwNFxow3QeGlXwSO9Eicf13/EokJcuCT2OKyb\\nZ4f4AyWn4TyiRKL5+f6GLmVbY/Xh8WlbEwcdo4IBlDCCAZAwHwYDVR0jBBgwFoAU\\ntIls66z+H6uxDhqbFRFUGBfXPLswWwYDVR0gBFQwUjBQBggrBgEFBQcCATBEMEIG\\nCCsGAQUFBwIBFjZodHRwOi8vbXB1cy5jbWNhLm5ldDo5MDkwL2ZpbGVzL2Rvd25s\\nb2FkY2VudGVyL2Nwcy5kb2MwZgYDVR0fBF8wXTBboC+gLYYraHR0cHM6Ly9tcHVz\\nLmNtY2EubmV0OjkwOTAvc20yY3JsL0dNY3JsLmNybKIopCYwJDELMAkGA1UEBhMC\\nQ04xFTATBgNVBAMMDENNQ0EgUm9vdCBDQTBMBggrBgEFBQcBAQRAMD4wPAYIKwYB\\nBQUHMAKGMGh0dHBzOi8vbXB1cy5jbWNhLm5ldDo5MDkwL2NybGRvd25sb2FkL0dN\\nY2VyLnppcDAgBggqgRzQFAQBBAQUDBI5MTEyMDExNjcyMjk5NzQwNEcwDgYDVR0P\\nAQH/BAQDAgbAMB0GA1UdDgQWBBTNWsvbK8XteZ7ElltKev6uz98v5jAJBgNVHRME\\nAjAAMAwGCCqBHM9VAYN1BQADRwAwRAIgNlIff9FGIH3Moi4J3vIQGAEpXCGUR8Op\\nUTAaLQs8vwUCIEogd97TeUBynlosRulHGZhQsbrXXhxKj8fIExghsMw6==\\n-----END CERTIFICATE-----\\n");
        data.put("algType", "1");
        data.put("certType", "1");
        data.put("encCert", "加密证书私钥");
        data.put("encPriKey", "加密证书私钥");

        ConnBaseResponse<Map<String, Object>> result = new ConnBaseResponse<>();
        result.setStatusCode("200");
        result.setMessage("success");
        result.setData(data);
        result.setTimestamp(new Date().toString());
        return result;
    }

    /**
     * 身份验证 挑战
     *
     * @return 模拟响应数据
     */
    @PostMapping("/identityVerify")
    public ConnBaseResponse<Map<String, Object>> mockIdentityVerify(@RequestBody IdentityVerifyVO identityVerifyVO) {
        Map<String, Object> data = new HashMap<>();
        data.put("nonce", "服务侧校验标识");
        data.put("timeout", "过期时间");

        ConnBaseResponse<Map<String, Object>> result = new ConnBaseResponse<>();
        result.setStatusCode("200");
        result.setMessage("success");
        result.setData(data);
        result.setTimestamp(new Date().toString());
        return result;
    }

    /**
     * 身份验证 应答
     *
     * @return 模拟响应数据
     */
    @PostMapping("/identityVerifyNonce")
    public ConnBaseResponse<Map<String, Object>> mockIdentityVerifyNonce(@RequestBody IdentityVerifyNonceVO identityVerifyNonceVO) {
        Map<String, Object> data = new HashMap<>();
        data.put("tokenName", "tokenName");
        data.put("tokenValue", "tokenValue");
        data.put("loginId", "loginId");
        data.put("timeout", "timeout");

        ConnBaseResponse<Map<String, Object>> result = new ConnBaseResponse<>();
        result.setStatusCode("200");
        result.setMessage("success");
        result.setData(data);
        result.setTimestamp(new Date().toString());
        return result;
    }

    /**
     * 节点目录列表查询
     *
     * @return 模拟响应数据
     */
    @PostMapping("/regionSyncListQuery")
    public ConnBaseResponse<ServiceNodeQueryResponse> mockRegionSyncListQuery(@RequestBody ConnectivityBaseRequest connectivityBaseRequest) {
        ConnBaseResponse<ServiceNodeQueryResponse> result = new ConnBaseResponse<>();

        try {

            //创建交易策略列表
            List<ServiceNodeQueryResponse.ServiceNodeList> serviceNodes = generateServiceNodes();

            //创建响应对象
            ServiceNodeQueryResponse response = new ServiceNodeQueryResponse();
            response.setLimit(connectivityBaseRequest.getLimit());
            response.setOffset(connectivityBaseRequest.getOffset());
            response.setTotal(serviceNodes.size());

            response.setServiceNodeList(serviceNodes);

            result.setData(response);
            result.setStatusCode("200");
            result.setMessage("调用成功");
            result.setTimestamp(String.valueOf(System.currentTimeMillis()));
        } catch (Exception e) {
            result.setStatusCode("500");
            result.setMessage("模拟数据生成失败：" + e.getMessage());
            result.setTimestamp(String.valueOf(System.currentTimeMillis()));
        }

        return result;
    }

    /**
     * 生成业务节点假数据
     */
    private List<ServiceNodeQueryResponse.ServiceNodeList> generateServiceNodes() {
        List<ServiceNodeQueryResponse.ServiceNodeList> serviceNodes = new ArrayList<>();

        // 添加多个业务节点数据
        serviceNodes.add(createServiceNode(
                "国家政务数据交换平台",
                "SN202411070001",
                "国家级政务数据交换与共享平台，支持跨部门数据流通和业务协同，提供安全可靠的数据服务",
                "V2.1.0",
                "国家级平台，符合等保三级要求",
                "国家政务服务中心",
                "91110000100012345A",
                Arrays.asList(
                        createAddress("2", "192.168.1.100", "data-exchange.gov.cn", "https://data-exchange.gov.cn/api/v1"),
                        createAddress("4", "192.168.1.101", "auth.gov.cn", "https://auth.gov.cn/api/v1")
                )
        ));
        serviceNodes.add(createServiceNode(
                "金融风险监控数据中心",
                "SN202411070002",
                "金融机构风险监控与数据分析平台，实时监控金融交易风险，支持反欺诈和信用评估",
                "V1.5.3",
                "金融行业专用，7x24小时运维",
                "中国金融监管局",
                "91110000100023456B",
                Arrays.asList(
                        createAddress("3", "10.0.1.50", "risk-monitor.finance.cn", "https://risk-monitor.finance.cn/api"),
                        createAddress("5", "10.0.1.51", "service.finance.cn", "https://service.finance.cn/api")
                )
        ));
        serviceNodes.add(createServiceNode(
                "环境监测数据平台",
                "SN202411070007",
                "环境质量监测与数据分析平台，支持空气质量、水质、噪声等环境数据的实时监控",
                "V1.8.2",
                "物联网设备接入，实时告警",
                "环境保护部",
                "91110000100078901G",
                Arrays.asList(
                        createAddress("3", "172.17.1.100", "env-monitor.gov.cn", "https://env-monitor.gov.cn/api"),
                        createAddress("5", "172.17.1.101", "env-data.gov.cn", "https://env-data.gov.cn/api")
                )
        ));

        return serviceNodes;
    }

    /**
     * 创建业务节点对象
     */
    private ServiceNodeQueryResponse.ServiceNodeList createServiceNode(
            String entryName,
            String serviceNodeId,
            String introduction,
            String version,
            String reserveNotes,
            String enterpriseName,
            String enterpriseIdentityId,
            List<ServiceNodeQueryResponse.ServiceNodeAddress> addresses) {

        ServiceNodeQueryResponse.ServiceNodeList node = new ServiceNodeQueryResponse.ServiceNodeList();
        node.setEntryName(entryName);
        node.setServiceNodeId(serviceNodeId);
        node.setIntroduction(introduction);
        node.setVersion(version);
        node.setReserveNotes(reserveNotes);
        node.setEnterpriseName(enterpriseName);
        node.setEnterpriseIdentityId(enterpriseIdentityId);
        node.setAddresses(addresses);

        return node;
    }

    /**
     * 创建地址对象
     */
    private ServiceNodeQueryResponse.ServiceNodeAddress createAddress(
            String type,
            String ip,
            String domainName,
            String apiUrl) {

        ServiceNodeQueryResponse.ServiceNodeAddress address = new ServiceNodeQueryResponse.ServiceNodeAddress();
        address.setType(type);
        address.setIp(ip);
        address.setDomainName(domainName);
        address.setApiUrl(apiUrl);

        return address;
    }

    /**
     * 获取数据交易指令
     *
     * @return 模拟响应数据
     */
    @PostMapping("/tradingStrategyGrant")
    public ConnBaseResponse<TradingStrategyGrantResponse> mockTradingStrategyGrant(
            @RequestBody ConnectivityBaseRequest connectivityBaseRequest) {
        ConnBaseResponse<TradingStrategyGrantResponse> result = new ConnBaseResponse<>();

        try {
            //创建分页信息
            TradingStrategyGrantResponse.Pagination pagination = new TradingStrategyGrantResponse.Pagination();
            pagination.setTotal(20);
            pagination.setPage(1);
            pagination.setSize(10);

            //创建交易策略列表
            List<TradingStrategyGrantResponse.TradingStrategy> tradingStrategies = generateMockTradingStrategies();

            //创建响应对象
            TradingStrategyGrantResponse response = new TradingStrategyGrantResponse();
            response.setPagination(pagination);
            response.setData(tradingStrategies);

            result.setData(response);
            result.setStatusCode("200");
            result.setMessage("调用成功");
            result.setTimestamp(String.valueOf(System.currentTimeMillis()));
        } catch (Exception e) {
            result.setStatusCode("500");
            result.setMessage("模拟数据生成失败：" + e.getMessage());
            result.setTimestamp(String.valueOf(System.currentTimeMillis()));
        }

        return result;
    }

    /**
     * 生成模拟交易策略数据
     */
    private List<TradingStrategyGrantResponse.TradingStrategy> generateMockTradingStrategies() {
        List<TradingStrategyGrantResponse.TradingStrategy> strategies = new ArrayList<>();

        // 金融行业策略
        strategies.add(createTradingStrategy(
                "TS202411060001", "金融风控数据交易合约", "金融机构风险控制数据分析",
                System.currentTimeMillis() + "", System.currentTimeMillis() + 2592000000L + "",
                "BUYER_FIN_001", "SELLER_FIN_001", "CTRL_FIN_001",
                "实时数据流，加密传输，每日限额5000条", 1, "高风险业务监控",
                5000, "[{\"id\":\"DP_FIN_001\",\"name\":\"信用评分数据\"}]",
                "{\"securityLevel\":\"high\",\"compliance\":\"FINRA\"}", "按条计费", "条", 100,
                base64Encode("金融数据采用TLS1.3加密传输，数据格式为JSON"), "financial_delivery.pdf", "金融业"
        ));
        // 医疗行业策略
        strategies.add(createTradingStrategy(
                "TS202411060002", "医疗健康数据分析", "患者健康数据匿名化分析",
                System.currentTimeMillis() - 86400000L + "", System.currentTimeMillis() + 7776000000L + "",
                "BUYER_MED_001", "SELLER_MED_001", "CTRL_MED_001",
                "批量传输，每周更新，HIPAA合规", 2, "患者隐私保护",
                2000, "[{\"id\":\"DP_MED_001\",\"name\":\"匿名诊疗记录\"}]",
                "{\"hipaaCompliant\":true,\"dataType\":\"EMR\"}", "按次计费", "次", 5000,
                base64Encode("医疗数据脱敏处理，符合HIPAA标准"), "medical_protocol.docx", "医疗卫生"
        ));
        return strategies;
    }


    /**
     * 创建交易策略对象的辅助方法
     */
    private TradingStrategyGrantResponse.TradingStrategy createTradingStrategy(
            String tradingStrategyCode, String tradingStrategyName, String tradingStrategyContent,
            String tradingStrategyTime, String tradingStrategyEndTime, String buyerConnectorCode,
            String sellerConnectorCode, String ctrlInstructionId, String transactionExecutionStrategy,
            Integer deliveryStatus, String transactionNotes, Integer dataProductTransactionCount,
            String dataProductListInfo, String others, String measureMethod, String unit,
            Integer price, String deliveryInfo, String deliveryInfoFileName, String industry) {

        TradingStrategyGrantResponse.TradingStrategy strategy = new TradingStrategyGrantResponse.TradingStrategy();

        strategy.setTradingStrategyCode(tradingStrategyCode);
        strategy.setTradingStrategyName(tradingStrategyName);
        strategy.setTradingStrategyContent(tradingStrategyContent);
        strategy.setTradingStrategyTime(tradingStrategyTime);
        strategy.setTradingStrategyEndTime(tradingStrategyEndTime);
        strategy.setBuyerConnectorCode(buyerConnectorCode);
        strategy.setSellerConnectorCode(sellerConnectorCode);
        strategy.setCtrlInstructionId(ctrlInstructionId);
        strategy.setTransactionExecutionStrategy(transactionExecutionStrategy);
        strategy.setDeliveryStatus(deliveryStatus);
        strategy.setTransactionNotes(transactionNotes);
        strategy.setDataProductTransactionCount(dataProductTransactionCount);
        strategy.setDataProductListInfo(dataProductListInfo);
        strategy.setOthers(others);
        strategy.setMeasureMethod(measureMethod);
        strategy.setUnit(unit);
        strategy.setPrice(price);
        strategy.setDeliveryInfo(deliveryInfo);
        strategy.setDeliveryInfoFileName(deliveryInfoFileName);
        strategy.setIndustry(industry);

        return strategy;
    }


    /**
     * Base64编码辅助方法
     */
    private String base64Encode(String text) {
        try {
            return Base64.getEncoder().encodeToString(text.getBytes(StandardCharsets.UTF_8));
        } catch (Exception e) {
            return "RVJST1IgRU5DT0RJTkc=";
        }
    }


    /**
     * 交易指令数据交付状态上报
     *
     * @return 模拟响应数据
     */
    @PostMapping("/deliveryStatusReport")
    public ConnBaseResponse<Map<String, Object>> mockDeliveryQuery(@RequestBody DeliveryStatusReportVO deliveryStatusReportVO) {

        ConnBaseResponse<Map<String, Object>> result = new ConnBaseResponse<>();
        result.setStatusCode("200");
        result.setMessage("success");

        // 构造模拟响应数据
        Map<String, Object> data = new HashMap<>();
        result.setData(data);

        return result;
    }
}